package com.victualler.product.goods.repository.impl;

import com.victualler.core.base.repository.impl.BaseQueryRepositoryImpl;
import com.victualler.core.common.dto.PageDto;
import com.victualler.product.goods.dto.request.GoodsShowRequestDto;
import com.victualler.product.goods.entity.GoodsMainDao;
import com.victualler.product.goods.repository.GoodsMainQueryRepository;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @Aouthor Guoshichang
 * @Date 9:34 on 2018/6/27.
 * @Function 封装用于复杂sql查询的API. 为每个实体的repository层提供便利操作
 */
@Component
public class GoodsMainQueryRepositoryImpl extends BaseQueryRepositoryImpl<GoodsMainDao,Long> implements GoodsMainQueryRepository {

    /**
     * @author Guoshichang
     * @since 13:39 on 2018/7/7.
     * @param goodsShowRequestDto
     * @param pageNo
     * @param limit
     * @Function  根据条件入参PermissionRequestDto动态分页查询权限
     */
    public PageDto<GoodsMainDao> getGoodsByRequestDto(GoodsShowRequestDto goodsShowRequestDto, int pageNo, int limit) {
        String goodsMainTable = this.getTableName(GoodsMainDao.class);
        StringBuffer sql = new StringBuffer("select a.*,IFNULL(tp2.type,tp.type) from " + goodsMainTable + " a ");
        //引入5.8店星标
        sql.append("  LEFT JOIN goods_type_detail tp on tp.parent_id = a.id and tp.type = 'CT0001'  ");
        //引入精品店星标
        sql.append("  LEFT JOIN goods_type_detail tp2 on tp2.parent_id = a.id and tp2.type = 'CT0008'  ");
        sql.append(" where 1=1 ");
        Map<String,Object> params = new HashMap<>();
        if (goodsShowRequestDto.getName() != null) {
            sql.append(" and a.name like :name ");
            params.put("name","%" + goodsShowRequestDto.getName() + "%");
        }
        //调整从主表查询
        if (goodsShowRequestDto.getType() != null) {
            sql.append(" and a.goods_type = :type ");
            params.put("type",goodsShowRequestDto.getType());
        }
        if (goodsShowRequestDto.getGroupType() != null) {
            sql.append(" and a.group_type = :groupType ");
            params.put("groupType",goodsShowRequestDto.getGroupType());
        }
        if (goodsShowRequestDto.getVenderName() != null) {
            sql.append(" and a.vender_name Like :venderName ");
            params.put("venderName","%" + goodsShowRequestDto.getVenderName() + "%");
        }
        if (goodsShowRequestDto.getState() != null) {
            sql.append(" and a.state = :state ");
            params.put("state",goodsShowRequestDto.getState());
        }
        sql.append(" order by a.create_Date Desc");
        return this.queryPageBySql(sql.toString(),params,GoodsMainDao.class,pageNo,limit);
    }
}
